﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace MetaDrive.Core
{ 
    public class CreateChildTargetItem : ICreateTargetItem
    {
        public string FileNameMask { get; private set; }

        public CreateChildTargetItem(string fileNameMask)
        {
            this.FileNameMask = fileNameMask;
        }

        public EnvDTE.ProjectItem Create(EnvDTE.ProjectItem projectItem)
        {
            EnvDTE.ProjectItem childProjectItem = null;

            string filename = projectItem.get_FileNames(0);
            string filenameChild = Path.Combine(Path.GetDirectoryName(filename),
                                        string.Format("{0}.g{1}",
                                        Path.GetFileNameWithoutExtension(filename),
                                        Path.GetExtension(projectItem.Name)));

            foreach (EnvDTE.ProjectItem item in projectItem.ProjectItems)
            {
                if (string.Compare(item.get_FileNames(0), filenameChild, true) == 0)
                {
                    childProjectItem = item;
                    break;
                }
            }

            if (childProjectItem != null && childProjectItem.Document != null)
                childProjectItem.Document.Close(EnvDTE.vsSaveChanges.vsSaveChangesYes);

            File.WriteAllText(filenameChild, string.Empty);

            if (childProjectItem == null)
                childProjectItem = projectItem.ProjectItems.AddFromFile(filenameChild);

            return childProjectItem;
        }
    }
}
